package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.reactive.TransactionalOperator;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName: DishServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author: Zhang Peiyuan
 * @Create: 2024-12-18-17:37
 * @Version: v1.0
 */
@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper SetmealDishMapper;

    /**
     * 保存菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveDish(DishDTO dishDTO) {
        // 转化DTO为实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 如果没有传递status, 就赋值为0
        if(dish.getStatus()==null){
            dish.setStatus(0);
        }
        // 将菜品添加入dish表
        dishMapper.insert(dish);
        // 将菜品的口位加入表dish_flavor表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 有才加入
        if (flavors != null && !flavors.isEmpty()){
            for(DishFlavor flavor : flavors){
                // 由于dish.getId()是随机自增的，所以在插入dish表后，才可以获取到id
                flavor.setDishId(dish.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    @Override
    public PageResult queryDishPage(DishPageQueryDTO dishPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 返回给前端是 DishVO, 因为这里涉及到多表查询
        Page<DishVO> result = dishMapper.selectPage(dishPageQueryDTO);
        // 返回分页结果
        return new PageResult(result.getTotal(), result.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional
    public void deleteDishBatch(List<Long> ids) {
        if(ids != null && !ids.isEmpty()){
            for(Long id: ids){
                // 如果status == 1, 则不删除
                Integer status = dishMapper.selectStatusById(id);
                if(status == null ||  status == 1){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
            }
            for(Long id: ids){
                // 如果status == 0, 则删除
                Integer count = SetmealDishMapper.selectCountByDishid(id);
                if(count > 0){
                    throw new DeletionNotAllowedException((MessageConstant.DISH_BE_RELATED_BY_SETMEAL));
                }
            }

            // 正确情况下，删除
            // 执行效率略低
            /*for(Long id: ids){
                // 删除dish数据的同时也要删除对应的口味
                dishFlavorMapper.deleteByDishId(id);
                dishMapper.deleteById(id);
            }*/

            // 使用动态sql, 一次性删除
            dishMapper.deleteByIds(ids);
            dishFlavorMapper.deleteByDishIds(ids);
        }

    }

    @Override
    public DishVO getDishById(Long id) {
        // 在dish表中查询基础数据
        Dish dishBase = dishMapper.selectById(id);
        // 在flavor表中查询口味数据
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        // 合并查询到的数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dishBase, dishVO);
        dishVO.setFlavors(flavors);
        // 返回数据
        return dishVO;
    }

    /**
     * 更新菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateDishWithFalvor(DishDTO dishDTO) {
        // 更新dish表中的内容
        Dish dishBase = new Dish();
        BeanUtils.copyProperties(dishDTO, dishBase);
        dishMapper.update(dishBase);
        // 删除原有的口味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        // 添加新的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && !flavors.isEmpty()){
            for(DishFlavor flavor: flavors){
                flavor.setDishId(dishDTO.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    /**
     * 查询菜品列表
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> queryDishList(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.selectList(dish);
    }

    /**
     * 更新菜品状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish build = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(build);
    }
}
